package com.mainbo.androidframework.utils;

import java.io.IOException;

import android.text.TextUtils;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Created by robin on 13-10-11.
 */
public class JsonUtility {
	private static final String TAG = JsonUtility.class.getSimpleName();
	private static final ObjectMapper objectMapper = new ObjectMapper();

	static {
		objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	}
	public static ObjectMapper getObjectMapper() {
		return objectMapper;
	}

	public static <T> T readValue(String arg0, Class<T> arg1)
			throws IOException, JsonParseException, JsonMappingException {
		return objectMapper.readValue(arg0, arg1);
	}

	public static <T> T readValue(String arg0, TypeReference<T> typeReference)
			throws IOException {
        return objectMapper.readValue(arg0, typeReference);
    }
	public static String writeValueAsString(Object arg0)
			throws JsonProcessingException {
		return objectMapper.writeValueAsString(arg0);
	}

	/**
	 * json String转为数据对象.
	 * 
	 * @param str
	 *            json字符串
	 * @param clazz
	 *            数据对象的类型.
	 * @return 数据对象
	 */
	public static <T> T stringToObject(String str, Class<T> clazz) {
		T obj = null;
		if (clazz != null && !TextUtils.isEmpty(str)) {
			try {
				obj = readValue(str, clazz);
			} catch (JsonParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JsonMappingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		// LogUtil.d(TAG, "stringToObject obj : " + obj);
		return obj;
	}

	/**
	 * 数据对象转为json字符串.
	 * 
	 * @param obj
	 * @return json字符串.
	 */
	public static String objectToString(Object obj) {
		String str = null;
		try {
			str = JsonUtility.writeValueAsString(obj);
		} catch (JsonProcessingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// LogUtil.d(TAG, "objectToString str : " + str);
		return str;
	}

}
